package com.beiding.my.common;

import com.google.common.base.Joiner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Cache {

    private static Map pool = new HashMap();

    private static List<String> cacheKeys = new ArrayList<>();

    public static void put(Object value, Object space, Object... keys) {

        String cacheKey = space + "-" + Joiner.on("-").join(keys);

        if (cacheKeys.contains(cacheKey)) {
            throw new RuntimeException("重复key,请检查:" + cacheKey);
        }
        cacheKeys.add(cacheKey);

        System.out.println("放入缓存:   " + cacheKey + "   " + value);
        Map map = (Map) pool.computeIfAbsent(space, k -> new HashMap<>());
        //进行逐层操作
        for (int i = 0; i < keys.length - 1; i++) {
            map = (Map) map.computeIfAbsent(keys[i], k -> new HashMap<>());
        }
        map.put(keys[keys.length - 1], value);
    }

    public static Object get(Object space, Object... keys) {

        Map map = (Map) pool.computeIfAbsent(space, k -> new HashMap<>());
        for (int i = 0; i < keys.length - 1; i++) {
            map = (Map) map.computeIfAbsent(keys[i], k -> new HashMap<>());
        }
        return map.get(keys[keys.length - 1]);
    }

    public static <T> T computeIfAbsent(Get<T> get, Object space, Object... keys) {
        T r = (T) get(space, keys);
        if (r == null) {
            synchronized (Cache.class) {
                if ((r = (T) get(space, keys)) == null) {
                    r = get.create();
                    if (r == null) {
                        throw new NullPointerException("生成的缓存值不能为空");
                    }
                    put(r, space, keys);
                }
            }
        }
        return r;
    }

   public interface Get<T> {
        T create();
    }


}
